import os
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot
from src.utils.downloader import Downloader


class AvatarDownloadWorker(QObject):
    finished = pyqtSignal(str)
    log_signal = pyqtSignal(str)

    def __init__(self, url, dest_dir, filename=None, timeout=20):
        super().__init__()
        self.url = url
        self.dest_dir = dest_dir
        self.filename = filename
        self.timeout = timeout

    @pyqtSlot()
    def start(self):
        try:
            urls = [(self.url, self.filename)] if self.filename else [self.url]
            downloader = Downloader(
                urls=urls,
                dest_dir=self.dest_dir,
                max_workers=1,
                timeout=self.timeout
            )
            # 连接日志信号
            downloader.log_signal.connect(self.log_signal)
            # 只下载一个文件
            downloader.start()
            # 查找下载结果
            out_name = self.filename or os.path.basename(self.url.split("?", 1)[0])
            out_path = os.path.join(self.dest_dir, out_name)
            if os.path.exists(out_path):
                self.finished.emit(out_path)
            else:
                self.finished.emit("")
        except Exception as e:
            self.log_signal.emit(f"[ERROR] 头像下载失败: {e}")
            self.finished.emit("")
